package com.sl.eurekaserver.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import rx.Subscriber;
import rx.observables.BlockingObservable;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.sl.eurekaserver.command.UserObservableCommand;
import com.sl.eurekaserver.entity.User;

/**
 * 响应方式发送请求（观察订阅模式）
 * @author 舒莉
 *
 */
@RestController
public class UserObservableController {

	@Autowired
	private RestTemplate restTemplate;
	
	@RequestMapping(value="/getUser")
	public void getUser(){
		
		//没有订阅者也会执行的方式
		rx.Observable<User> ho=new UserObservableCommand(com.netflix.hystrix.HystrixObservableCommand.Setter.withGroupKey(
		        HystrixCommandGroupKey.Factory.asKey("")),restTemplate,"xxx").observe();
		
		 //创建订阅者
		Subscriber<User> subscriber = new Subscriber<User>() {

			@Override
			public void onCompleted() {
				System.out.println("onCompleted");
			}

			@Override
			public void onError(Throwable e) {
				
			}

			@Override
			public void onNext(User t) {
				System.out.println("onNext");
			}
		};
		
		//订阅
		ho.subscribe(subscriber);
	}
	
	@RequestMapping(value="/getUser2")
	public void getUser2(){
		
		try {
			//必须有订阅者才能执行的方式
			rx.Observable<User> ho=new UserObservableCommand(com.netflix.hystrix.HystrixObservableCommand.Setter.withGroupKey(
					HystrixCommandGroupKey.Factory.asKey("")),restTemplate,"xxx").toObservable();
			List<User> list=new ArrayList<>();
			BlockingObservable<User> blockingObservable=ho.toBlocking();
			Future<User> future=blockingObservable.toFuture();
			User user=future.get();
		    System.out.println(user.toString());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//注意捕获异常
	}
}
